package com.xuecheng.media.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.xuecheng.api.content.model.dto.CourseBaseDTO;
import com.xuecheng.api.media.AliyunVodApi;
import com.xuecheng.api.media.aliyun.VodUploadRequest;
import com.xuecheng.api.media.aliyun.VodUploadToken;
import com.xuecheng.api.media.model.dto.MediaDTO;
import com.xuecheng.api.media.model.vo.MediaVO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.SecurityUtil;
import com.xuecheng.media.common.constant.MediaErrorCode;
import com.xuecheng.media.common.utils.AliyunVODUtil;
import com.xuecheng.media.convert.MediaConvert;
import com.xuecheng.media.entity.Media;
import com.xuecheng.media.service.AliyunVodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * @author by 高鹏
 * @Date 2021/12/14
 * @Description
 */
@Slf4j
@RestController
public class AliyunVodController implements AliyunVodApi {

    @Value("${aliyun.region}")
    private String region;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    private AliyunVodService aliyunVodService;

    /**
     * 生成上传凭证
     *
     * @param uploadRequest
     * @return
     */
    @Override
    @PostMapping("media/vod-token")
    public VodUploadToken generateUploadToken(@RequestBody VodUploadRequest uploadRequest) {


        // PS: 只要和本项目中微服务之外的内容要产生交互，必须要进行try-catch处理
        //   交互方：aliyun（第三方服务）
        //   原因：网络（不稳定因素）
        try {
            // 1.初始化客户端
            DefaultAcsClient client = AliyunVODUtil.initVodClient(region, accessKeyId, accessKeySecret);

            // 2.创建请求对象并获得响应对象
            CreateUploadVideoResponse response = AliyunVODUtil.createUploadVideo(client, uploadRequest.getTitle(), uploadRequest.getFileName());

            // 3.解析响应数据
            VodUploadToken token = new VodUploadToken();

            token.setVideoId(response.getVideoId());
            token.setUploadAddress(response.getUploadAddress());
            token.setUploadAuth(response.getUploadAuth());
            token.setRequestId(response.getRequestId());

            return token;

        } catch (Exception e) {
            // printStackTrace：将程序中的所有调用关系的栈信息进行打印-日志（日志文件-IO）
            // 用户大量请求
            // e.printStackTrace();  //丢工作

            // 异常信息的说明
            // 1.只将错误信息记录
            // 2.将错误信息隐藏并返回友好提示
            String message = e.getMessage();
            log.error(MediaErrorCode.E_140011.getDesc() + " : {}", message);

            // throw new BusinessException();
            // 编译器的问题：只看代码，不管代码中方法调用的结果内容
            ExceptionCast.cast(CommonErrorCode.UNKOWN);
            return null;
        }
    }

    /**
     * 刷新凭证
     *
     * @param videoId
     * @return
     */
    @Override
    @GetMapping("media/refresh-vod-token/{videoId}")
    public VodUploadToken refreshUploadToken(@PathVariable String videoId) {

        try {
            // 1.初始化客户端
            DefaultAcsClient client = AliyunVODUtil.initVodClient(region, accessKeyId, accessKeySecret);

            // 2.创建请求对象并获得响应对象
            RefreshUploadVideoResponse response = AliyunVODUtil.refreshUploadVideo(client, videoId);

            // 3.解析响应数据
            VodUploadToken token = new VodUploadToken();

            token.setVideoId(response.getVideoId());
            token.setUploadAddress(response.getUploadAddress());
            token.setUploadAuth(response.getUploadAuth());
            token.setRequestId(response.getRequestId());

            return token;

        } catch (Exception e) {

            String message = e.getMessage();
            log.error(MediaErrorCode.E_140015.getDesc() + " : {}", message);

            ExceptionCast.cast(CommonErrorCode.UNKOWN);
            return null;
        }

    }

    /**
     * 保存媒资信息
     *
     * @param vo
     * @return
     */
    @PostMapping("/media")
    @Override
    public MediaDTO createMedia(@RequestBody MediaVO vo) {
        MediaDTO mediaDTO = MediaConvert.INSTANCE.vo2dto(vo);
        Long companyId = SecurityUtil.getCompanyId();
        MediaDTO dto = aliyunVodService.createMedia(mediaDTO, companyId);
        return dto;
    }


    /**
     * 媒资查询
     *
     * @param params
     * @param mediaVO
     * @return
     */
    @PostMapping("/media/list")
    @Override
    public PageVO queryMediaVodList(PageRequestParams params, MediaVO mediaVO) {

        MediaDTO mediaDTO = MediaConvert.INSTANCE.vo2dto(mediaVO);
        PageVO pageVO = aliyunVodService.queryMediaVodList(params, mediaDTO);
        return pageVO;
    }

    /**
     * @param mediaId
     * @return
     */
    @Override
    @GetMapping("/media/preview/{mediaId}")
    public String previewMedia(@PathVariable Long mediaId) {

        Long companyId = SecurityUtil.getCompanyId();

        String vodUrl = aliyunVodService.getVODUrl(mediaId, companyId);

        return vodUrl;
    }


    @DeleteMapping("media/{mediaId}")
    @Override
    public Boolean deleteMedia(@PathVariable Long mediaId) {
        Long companyId = SecurityUtil.getCompanyId();
        Boolean aBoolean = aliyunVodService.deleteMedia(mediaId, companyId);
        return aBoolean;
    }
}
